package com.itgacl.magic4j.libcommon.component.license;

import com.itgacl.magic4j.libcommon.component.license.crypto.MD5Utils;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * 通过计算机信息生成可用许可
 *
 */
@Slf4j
public class LicenseSequences {

    /**
     * 将信息加密，并格式化为:<br/>
     * 字母单位: 4-4-8-16 <br/>
     * XXXX-XXXX-XXXXXXXX-XXXXXXXXXXXXXXXX
     *
     * @param str 待加密内容
     * @return
     */
    private static String genMd5Code(String str) {
        String txt = MD5Utils.encode(str);
        try {
            return formatCode(txt);
        } catch (Exception e) {
            log.error("MD5摘要失败！", e);
        }
        return null;
    }

    /**
     * 将很长的字符串以固定的位数分割开，以便于人类阅读
     *
     * @param str 待格式化内容
     * @return
     * @throws Exception
     */
    private static String formatCode(String str) throws Exception {
        if (str.length() != 32) throw new Exception("MD5信息长度不符合。");

        String c0 = str.substring(0, 4);
        String c1 = str.substring(4, 8);
        String c2 = str.substring(8, 16);
        String c3 = str.substring(16, 32);

        String newStr = c0 + "-" + c1 + "-" + c2 + "-" + c3;
        return newStr;
    }

    /**
     * 获取本机的机器码后，进行格式化及转大写
     *
     * @return 机器码
     */
    public static String sequence() {
        String machineCode = MachineSerial.machineIp();

        return Objects.requireNonNull(genMd5Code(machineCode)).toUpperCase();
    }

    /**
     * 根据机器码生成sequence
     * @param machineCode
     * @return
     */
    public static String sequence(String machineCode) {
        return Objects.requireNonNull(genMd5Code(machineCode)).toUpperCase();
    }
}
